package com.zhoudb.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhoudb.blog.dto.Nav;
import com.zhoudb.blog.entity.*;
import com.zhoudb.blog.service.*;
import com.zhoudb.blog.util.ConversionUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: zhoudb
 * @Date: 2018-09-27 9:54
 */
@Controller
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleContentService articleContentService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private MenuService menuService;


    @PostMapping("/doLogin")
    public String doLogin(String username, String password,String rememberMe,HttpSession session) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //User user = (User) subject.getPrincipal();
            //登陆成功的话，放到session中
            //session.setAttribute("user", user);
            return "redirect:/admin/index";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/admin/login";
        }
    }

    @RequestMapping("/doLogout")
    public String doLogout() {
        Subject subject = SecurityUtils.getSubject();//取出当前验证主体
        if (subject != null) {
            subject.logout();//不为空，执行一次logout的操作，将session全部清空
        }
        return "login";
    }

    /**
     * 功能描述: 分类列表查询
     *
     * @param limit
     * @param page
     * @return
     * @author zhoudb
     * @date 2018/9/30 15:35
     */
    @RequestMapping("/showCategoryList")
    @ResponseBody
    public Map<String, Object> showCategoryList(long limit, long page) {
        Map<String, Object> resultMap = new HashMap<>(4);
        Page<Category> map = new Page<>();
        map.setCurrent(page);
        map.setSize(limit);
        QueryWrapper<Category> query = new QueryWrapper<>();
        //query.eq("name","gg");
        IPage<Category> list = categoryService.page(map, query);
        resultMap.put("code", 0);
        resultMap.put("count", list.getTotal());
        resultMap.put("data", list.getRecords());
        return resultMap;
    }

    @RequestMapping("/showCategory")
    @ResponseBody
    public List<Map<String, Object>> showCategory() {
        QueryWrapper<Category> query = new QueryWrapper<>();
        query.select("id", "name");
        return categoryService.listMaps(query);
    }

    @RequestMapping("/addOrEditCategory")
    @ResponseBody
    public Map<String, Object> addOrEditCategory(Category category) {
        Map<String, Object> resultMap = new HashMap<>(2);
        if (category.getId() == null) {
            category.setCreateBy(LocalDateTime.now());
        } else {
            category.setModifiedBy(LocalDateTime.now());
        }
        boolean success = categoryService.saveOrUpdate(category);
        resultMap.put("success", success);
        return resultMap;
    }

    @RequestMapping("/deleteCategory")
    @ResponseBody
    public Map<String, Object> deleteCategory(String id) {
        Map<String, Object> resultMap = new HashMap<>(2);
        List<String> delList = Arrays.asList(id.split(","));
        boolean success = categoryService.removeByIds(delList);
        resultMap.put("success", success);
        return resultMap;
    }

    @RequestMapping("/showArticleList")
    @ResponseBody
    public Map<String, Object> showArticleList(long limit, long page) {
        Map<String, Object> resultMap = new HashMap<>(4);
        Page map=new Page(page,limit);
        QueryWrapper query = new QueryWrapper<>();
        Page list=articleService.listPage(map,query);
        resultMap.put("code", 0);
        resultMap.put("count", list.getTotal());
        resultMap.put("data", list.getRecords());
        return resultMap;
    }

    @RequestMapping("/addOrEditArticle")
    @ResponseBody
    public Map<String, Object> addOrEditArticle(Article article) {
        Map<String, Object> resultMap = new HashMap<>(2);
        if (article.getId() == null) {
            article.setCreateBy(LocalDateTime.now());
        } else {
            article.setModifiedBy(LocalDateTime.now());
        }
        boolean success = articleService.saveOrUpdate(article);
        resultMap.put("success", success);
        return resultMap;
    }

    @RequestMapping("/deleteArticle")
    @ResponseBody
    public Map<String, Object> deleteArticle(String id) {
        Map<String, Object> resultMap = new HashMap<>(2);
        List<String> delList = Arrays.asList(id.split(","));
        boolean success = articleService.removeByIds(delList);
        resultMap.put("success", success);
        return resultMap;
    }

    @RequestMapping("/showArticle")
    @ResponseBody
    public ArticleContent showArticle(String articleId){
        QueryWrapper<ArticleContent> query = new QueryWrapper<>();
        query.eq("article_id",articleId);
        return  articleContentService.getOne(query);
    }

    @RequestMapping("/saveArticle")
    @ResponseBody
    public Map<String, Object> saveArticle(ArticleContent articleContent) {
        Map<String, Object> resultMap = new HashMap<>(2);
        QueryWrapper<ArticleContent> query = new QueryWrapper<>();
        query.eq("article_id",articleContent.getArticleId());
        ArticleContent old=articleContentService.getOne(query);
        if (old == null) {
            articleContent.setCreateBy(LocalDateTime.now());
        } else {
            articleContent.setModifiedBy(LocalDateTime.now());
            articleContent.setId(old.getId());
        }
        boolean success = articleContentService.saveOrUpdate(articleContent);
        resultMap.put("success", success);
        return resultMap;
    }

    @RequestMapping("/showCommentList")
    @ResponseBody
    public Map<String, Object> showCommentList(long limit, long page) {
        Map<String, Object> resultMap = new HashMap<>(4);
        Page<Comment> map = new Page<>();
        map.setCurrent(page);
        map.setSize(limit);
        QueryWrapper<Comment> query = new QueryWrapper<>();
        IPage<Comment> list = commentService.page(map, query);
        resultMap.put("code", 0);
        resultMap.put("count", list.getTotal());
        resultMap.put("data", list.getRecords());
        return resultMap;
    }

    @RequestMapping("/deleteComment")
    @ResponseBody
    public Map<String, Object> deleteComment(String id) {
        Map<String, Object> resultMap = new HashMap<>(2);
        List<String> delList = Arrays.asList(id.split(","));
        boolean success = commentService.removeByIds(delList);
        resultMap.put("success", success);
        return resultMap;
    }

    @RequestMapping("/showMenuList")
    @ResponseBody
    public Map<String, Object> showMenuList(long limit, long page) {
        Map<String, Object> resultMap = new HashMap<>(4);
        Page map = new Page<>(page,limit);
        QueryWrapper query = new QueryWrapper<>();
        Page list=menuService.listPage(map,query);
        resultMap.put("code", 0);
        resultMap.put("count", list.getTotal());
        resultMap.put("data", list.getRecords());
        return resultMap;
    }

    @RequestMapping("/addOrEditMenu")
    @ResponseBody
    public Map<String, Object> addOrEditMenu(Menu menu) {
        Map<String, Object> resultMap = new HashMap<>(2);
        if (menu.getId() == null) {
            menu.setCreateBy(LocalDateTime.now());
        } else {
            menu.setModifiedBy(LocalDateTime.now());
        }
        boolean success = menuService.saveOrUpdate(menu);
        resultMap.put("success", success);
        return resultMap;
    }

    @RequestMapping("/deleteMenu")
    @ResponseBody
    public Map<String, Object> deleteMenu(String id) {
        Map<String, Object> resultMap = new HashMap<>(2);
        List<String> delList = Arrays.asList(id.split(","));
        boolean success = menuService.removeByIds(delList);
        resultMap.put("success", success);
        return resultMap;
    }

    @RequestMapping("/showMenu")
    @ResponseBody
    public List<Map<String, Object>> showMenu() {
        QueryWrapper<Menu> query = new QueryWrapper<>();
        query.select("id", "name");
        query.eq("level",1);
        query.orderByAsc("sort_id");
        return menuService.listMaps(query);
    }

    @RequestMapping("/listMenu")
    @ResponseBody
    public List<Nav> listMenu() {
        //查询出所有的一级菜单
        QueryWrapper<Menu> query1 = new QueryWrapper<>();
        query1.eq("level",1);
        List<Menu> menuList1=menuService.list(query1);
        //查询出所有的二级菜单
        QueryWrapper<Menu> query2 = new QueryWrapper<>();
        query2.eq("level",2);
        List<Menu> menuList2=menuService.list(query2);
        List<Nav> navlist=ConversionUtil.poList2dtoList(menuList1,Nav.class);

        //组装菜单列表
        for(Nav nav:navlist){
            if(CollectionUtils.isEmpty(nav.getMenuList())){
               for(Menu menu2:menuList2){
                   if(nav.getId().equals(menu2.getParentId())){
                       nav.getMenuList().add((Nav) ConversionUtil.po2dto(menu2,Nav.class));
                   }
               }
            }
        }
        return navlist;
    }
}
